//
//  KeychainManager.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/25.
//

import Foundation
import Security

let idfvKey = "idfvKey"

class KeychainManager {
    
    static let shared = KeychainManager()
    private init() {}
    
    // 保存数据到 Keychain (使用单个 key)
    func save(_ data: Data, forKey key: String) -> Bool {
        let query = [
            kSecValueData: data,
            kSecClass: kSecClassGenericPassword,
            kSecAttrAccount: key  // 使用 key 作为唯一标识
        ] as CFDictionary
        
        // 先删除已存在的值（避免重复）
        SecItemDelete(query)
        
        // 添加新值
        let status = SecItemAdd(query, nil)
        return status == errSecSuccess
    }
    
    // 从 Keychain 读取数据
    func read(forKey key: String) -> Data? {
        let query = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrAccount: key,
            kSecReturnData: true,
            kSecMatchLimit: kSecMatchLimitOne
        ] as CFDictionary
        
        var result: AnyObject?
        let status = SecItemCopyMatching(query, &result)
        
        return status == errSecSuccess ? result as? Data : nil
    }
    
    // 从 Keychain 删除数据
    func delete(forKey key: String) -> Bool {
        let query = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrAccount: key
        ] as CFDictionary
        
        let status = SecItemDelete(query)
        return status == errSecSuccess
    }
    
    // 保存字符串
    @discardableResult
    func saveString(_ string: String, forKey key: String) -> Bool {
        guard let data = string.data(using: .utf8) else { return false }
        return save(data, forKey: key)
    }
    
    // 读取字符串
    func readString(forKey key: String) -> String? {
        guard let data = read(forKey: key) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}
